import UIKit

///给定一个字符串 s，找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。

class Solution {
    func longestPalindrome(_ s: String) -> String {
        var maxnum = 0;
        if s.count > 0 {
            maxnum = 1;
        }else {
            return "";
        }
        var subText = "";
        let list = Array(s);
        var j = 0;
        for i in 1..<list.count {
            let nextStartIndex = j + 1;
            let lastSub = list[i];
            let firstSub = list[j];
            let contenxtStartIndex = list.index(list.startIndex, offsetBy: nextStartIndex);
            let contenxtEndIndex = list.index(list.startIndex, offsetBy: i);
            let contenxtSub = list[contenxtStartIndex..<contenxtEndIndex];
//            print("\(firstSub) -> \(contenxtSub)  -> \(lastSub)")
            if contenxtSub.contains(firstSub) || firstSub == lastSub {
                j = j + 1;
            }else if contenxtSub.contains(lastSub) {
                let index = contenxtSub.firstIndex(where: {$0 == lastSub});
                j = index! + 1;
            }else {
                maxnum = max(maxnum, contenxtSub.count + 2);
                let subIndex = s.index(s.startIndex, offsetBy: contenxtStartIndex);
                let endIndex = s.index(s.startIndex, offsetBy: contenxtEndIndex);
                subText = String(s[subIndex...endIndex]);
            }
        }
        return subText;
    }
}
let str = "babad";

